package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备管理Service业务层处理
 *
 * @author Katana
 * @date 2025-05-25
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private IoTDAClient client;
    
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;
    
    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }
    
    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }
    
    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }
    
    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }
    
    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }
    
    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }
    
    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //对接华为云API，获取产品列表
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表异常");
        }
        
        //将获取到的产品列表转为JSON字符串，存入Redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(response.getProducts()));
    }
    
    /**
     * 查询所有产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
        //1 从Redis中查询
        String json = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isBlank(json)) {
            return Collections.emptyList();
        }
        //2 解析JSON字符串，返回产品列表
        List<ProductSummary> summaryList = JSONUtil.toList(json, ProductSummary.class);
        
        //3 转换为ProductVo对象，返回
        List<ProductVo> productVoList = summaryList.stream().map(summary -> {
            return ProductVo.builder().productKey(summary.getProductId()).productName(summary.getName()).build();
        }).collect(Collectors.toList());
        return productVoList;
        
    }
    
    
    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(DeviceDto deviceDto) {
        //1 准备node_id和secret两个字段
        //1.1 前端没有传设备标识码，生成雪花算法值，当做唯一设备标识码
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        //1.2 uuid当做唯一设备密钥
        String secret = IdUtil.simpleUUID();
        //设备备注名称（设备描述）
        String deviceDescription = deviceDto.getRegisterDeviceRequest().getNickname();
        //2 判断设备名称是否重复
        Long deviceCount = lambdaQuery().eq(Device::getDeviceName, deviceDescription).count();
        if (deviceCount > 0) {
            throw new BaseException("设备名称重复");
        }
        //3 检查当前位置是否绑定相同产品(位置类型,绑定位置,产品类型都一样)
        Long count = lambdaQuery().eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .count();
        if (count > 0) {
            throw new BaseException("当前位置已绑定相同产品");
        }
        
        //4 注册设备到云平台
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        body.setNodeId(nodeId);
        body.setProductId(deviceDto.getProductKey());
        body.setDeviceName(deviceDescription);
        //设备备注名称（设备描述)
        body.setDescription(deviceDescription);
        body.setAuthInfo(authInfo);
        addDeviceRequest.setBody(body);
        AddDeviceResponse response = client.addDevice(addDeviceRequest);
        if (response == null || response.getHttpStatusCode() != 201) {
            throw new BaseException("注册设备到云端失败");
        }
        //5 保存设备信息到数据库
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        device.setIotId(response.getDeviceId());
        device.setNodeId(nodeId);
        device.setSecret(secret);
        device.setNickname(deviceDescription);
        device.setDeviceDescription(deviceDescription);
        
        String productName = this.getProductNameFromCache(deviceDto.getProductKey());
        device.setProductName(productName);
        this.save(device);
    }
    
    private String getProductNameFromCache(String productKey) {
        //1 从Redis中查询
        String json = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isBlank(json)) {
            return null;
        }
        //2 解析JSON字符串，返回产品列表
        List<ProductSummary> summaryList = JSONUtil.toList(json, ProductSummary.class);
        
        //3 筛选出指定产品
        Optional<ProductSummary> optional = summaryList.stream()
                .filter(summary -> summary.getProductId().equals(productKey))
                .findFirst();
        if (optional.isEmpty()) {
            return null;
        }
        //4 获取产品名称
        ProductSummary summary = optional.get();
        return summary.getName();
    }
    
    /**
     * 获取设备详细信息
     *
     * @param iotId
     */
    @Transactional
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1 根据iotId查询设备信息
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        //2 从华为云中查询设备详细信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("从云端查询设备详细信息失败");
        }
        //3 封装返回对象
        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        //3.1 拷贝表中设备信息,封装一些可以从项目配置文件中获取的信息
        BeanUtils.copyProperties(device, deviceDetailVo);
        deviceDetailVo.setBindingLocation(device.getBindingLocation());
        deviceDetailVo.setDeviceSecret(device.getSecret());
        //deviceDetailVo.setGmtCreate(device.getCreateTime());
        deviceDetailVo.setCreator(userService.selectUserById(Long.valueOf(device.getCreateBy())).getUserName());
        deviceDetailVo.setRegion(huaWeiIotConfigProperties.getRegionId());
        //3.2 华为云设备信息封装
        deviceDetailVo.setDeviceStatus(response.getStatus());
        deviceDetailVo.setDeviceDescription(response.getDescription());
        //响应的激活时间格式为：2019-03-03T08:10.111Z,需要转为yyyy-MM-dd HH:mm:ss格式的时间
        String activeTime = response.getActiveTime();
        if (StringUtils.isNotBlank(activeTime)) {
            deviceDetailVo.setGmtActive(DateUtil.parse(activeTime, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").toLocalDateTime().plusHours(8));
        }
        String createTime = response.getCreateTime();
        if (StringUtils.isNotBlank(createTime)) {
            deviceDetailVo.setGmtCreate(DateUtil.parse(createTime, "yyyyMMdd'T'HHmmss'Z'").toLocalDateTime().plusHours(8));
        }
        // 设置固件版本
        if (StringUtils.isNotBlank(response.getFwVersion())) {
            deviceDetailVo.setFirmwareVersion(response.getFwVersion());
        }
        return deviceDetailVo;
    }
    
    /**
     * 获取产品物模型详情
     *
     * @param productKey
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //参数校验
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response = client.showProduct(showProductRequest);
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("从华为云查询产品物模型详情失败");
        }
        
        JSONObject productModelInfo = null;
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilityList = response.getServiceCapabilities();
        if (CollUtil.isNotEmpty(serviceCapabilityList)) {
            productModelInfo = JSONUtil.parseObj(serviceCapabilityList.get(0));
        }
        return productModelInfo;
        
    }
    
    /**
     * 查询指定设备的物模型运行状态
     *
     * @param productKey
     * @param deviceName
     */
    @Override
    @Transactional
    public Map<String, Object> queryDevicePropertyStatus(String productKey, String deviceName) {
        
        //根据产品Id和设备名查询设备ID
        Device device = this.lambdaQuery().eq(Device::getProductKey, productKey).eq(Device::getDeviceName, deviceName).one();
        if (device == null) {
            throw new BaseException("没有此设备");
        }
        
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        //根据设备ID查询影子设备的信息
        request.setDeviceId(device.getIotId());
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        
        List<Map<String, Object>> list = new ArrayList<>();
        
        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'").plusHours(8);
        
        
        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("identifier", k);
            map.put("value", v);
            map.put("time", activeTime);
            list.add(map);
        });
        
        Map<String, Object> propertyStatusInfo = new HashMap<>();
        propertyStatusInfo.put("propertyStatusInfo", list);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", propertyStatusInfo);
        
        return result;
    }
    
    /**
     * 修改设备信息
     *
     * @param dto
     * @return
     */
    @Override
    public int editDevice(DeviceDto dto) {
        //根据设备id查询设备信息
        Device deviceDB = selectDeviceById(dto.getId());
        if (deviceDB == null) {
            throw new BaseException("没有此设备");
        }
        
        //1 将修改后的备注名称取出
        String deviceDescription = dto.getDeviceDescription();
        
        //2 更新到云端
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(deviceDB.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDescription(deviceDescription);
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 更新设备备注信息，调用失败");
        }
        
        //3 拷贝设备信息
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setNickname(deviceDescription);
        //4 将设备信息更新到数据库
        return updateDevice(device);
    }
    
    
    /**
     * 删除设备
     *
     * @param iotId
     * @return
     */
    @Override
    public int deleteDevice(String iotId) {
        //根据设备id查询设备信息
        Device deviceDB = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (deviceDB == null) {
            throw new BaseException("表中没有此设备");
        }
        //1 从云端删除设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        log.info("删除设备信息,云端接口返回值：{}", response);
        if (response == null) {
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
        //2 删除数据库设备信息
        return deleteDeviceById(deviceDB.getId());
    }
}
